class Solution(object):
    def makeConnected(self, n, connections):
        m = len(connections)
        if m < n - 1:
            return - 1
        p = [i for i in range(n)]
        self.c = n
        def find(x):
            if x == p[x]:
                return x
            else:
                p[x] = find(p[x])
                return p[x]

        def union(x, y):
            rootx = find(x)
            rooty = find(y)
            if rootx != rooty:
                if rootx < rooty:
                    p[rooty] = rootx
                else:
                    p[rootx] = rooty
                self.c -= 1

        for u, v in connections:
            union(u, v)

        return self.c - 1
